package com.ruoyi.livesass.api.sync;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.google.common.collect.Maps;
import com.ruoyi.livesass.LiveVideoService;
import com.ruoyi.livesass.api.domain.LbsGksc;
import com.ruoyi.livesass.api.mapper.LbsGkscMapper;
import com.ruoyi.livesass.api.service.LbsGkscService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.volcengine.model.livesaas.response.GetUserBehaviorListResponseAPIV2;
import com.volcengine.model.livesaas.response.GetUserBehaviorListResponseAPIV2.UserBehaviorV2;
import com.volcengine.model.livesaas.response.ListActivityAPIResponse;
import com.volcengine.model.livesaas.response.ListActivityAPIResponse.ListActivityAPIForm;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;

/**
 * @ClassName: LiveUserTimeDataSynService
 * @Description: TODO(直播用户观看时长 -主要统计 周  月数据  -每日一次)
 * @author 晏大兵
 * @date 2025年2月10日 上午11:13:23
 */
@Component("gkscSyn")
@Order(3)
public class LiveUserTimeDataSynService implements ApplicationRunner {
	
	private static final Logger LOG = LoggerFactory.getLogger(LiveUserTimeDataSynService.class);
	
	@Autowired
	LiveVideoService liveVideoService;
	
	@Autowired
	LbsGkscMapper lbsGkscMapper;
	
	@Autowired
	LbsGkscService lbsGkscService;
	
	@Autowired
	MemberMapper memberMapper;
	
	
	@Value("${custom.synTasks.liveUserTimeTask}")
	private String liveUserTimeTask;
	
	//@Value("${custom.hsSubUserName}")
	//private String hsSubUserName;
	
	@Value("${custom.synTaskEnable}")
	private boolean synTaskEnable;
	
    @Autowired
    private ISysConfigService configService;
    
    Map<String, JSONObject> repeatSubUserName = Maps.newHashMap();
	
	
	//@Scheduled(cron  = "${custom.synTasks.liveUserTimeTask}")
    public void performTask() throws Exception {
		if(!synTaskEnable) {
			return ;
		}
		System.out.println("直播用户观看时长开始 ：" + System.currentTimeMillis());
		
        try {
			this.syncLoadSysConfig();
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error("定时任务异常 | 重新执行");
			Thread.sleep(2000);
			performTask();
		}
        
        System.out.println("直播用户观看时长结束 ：" + System.currentTimeMillis());
    }
	

	@Override
	public void run(ApplicationArguments args) throws Exception {
		try {
			if(!synTaskEnable) {
				return ;
			}
			//this.syncLiveUserTime(hsSubUserName);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void syncLoadSysConfig() throws Exception {
		SysConfig sysConfig = configService.selectConfigByKey2("sys_config");
		if (null != sysConfig && !StrUtil.isBlankIfStr(sysConfig.getRemark())) {
			JSONObject sysConfigJsonObject = JSONObject.parseObject(sysConfig.getRemark());
			if (sysConfigJsonObject.containsKey("activityConfig")) {
				JSONArray activityConfigList = sysConfigJsonObject.getJSONArray("activityConfig");
				
				
				for (int i = 0; i < activityConfigList.size(); i++) { //去重subusername
					JSONObject item = activityConfigList.getJSONObject(i);
					repeatSubUserName.put(item.getString("subusername"), item);
				}
				
				for(String sunName : repeatSubUserName.keySet()) {
					this.syncLiveUserTime(sunName);
					//this.syncLiveUserTimeDataToDay(sunName, kssj, jssj);
				}
				
				/*
				for (int i = 0; i < activityConfigList.size(); i++) {
					JSONObject item = activityConfigList.getJSONObject(i);
					this.syncLiveUserTime(item.getString("subusername"));
				}*/
				
				
			}
		}
	}

	
	/**
	* @Title: syncLiveVideoFlows 
	* @Description: TODO(同步直播流量数据) 
	* @param     设定文件 
	* @return void    返回类型 
	 * @throws Exception 
	* @throws
	*/
	public void syncLiveUserTime(String userName) throws Exception {
		
		//首先查询出需要统计的直播间
		DateTime now = DateTime.now();
		String nowDayStr = now.toDateStr();
		DateTime nowDayTime = DateTime.of(nowDayStr, "yyyy-MM-dd");
		int pageNo = 1;
		int pageItemCount = 10000;
		int status = 4; //已结束的直播间
		String sortBy = "LiveTime";
		String sortOrder = "Desc";
		
		
		//更新最近一个月的观看时长
		DateTime offsetDay = nowDayTime.offsetNew(DateField.DAY_OF_YEAR, -1);
		DateTime offsetWeek = nowDayTime.offsetNew(DateField.WEEK_OF_YEAR, -1);
		DateTime offsetMonth = nowDayTime.offsetNew(DateField.MONTH, -1);
		
		long offsetDayTime = (offsetDay.toJdkDate().getTime() / 1000);
		long offsetWeekTime = (offsetWeek.toJdkDate().getTime() / 1000);
		long offsetMonthTime = (offsetMonth.toJdkDate().getTime() / 1000);
		ListActivityAPIResponse offsetMonthListActivityAPIResponse = liveVideoService.listActivity(pageNo, pageItemCount, userName, status, sortBy, sortOrder, offsetMonthTime);
		List<ListActivityAPIForm> offsetMonthListActivity = offsetMonthListActivityAPIResponse.getResult().getActivities();
		processOffsetMonth(offsetMonthListActivity, offsetDayTime, offsetWeekTime, offsetMonthTime);
		
		
	}
	
	
	
	/**
	* @Title: processOffsetMonth 
	* @Description: TODO(处理偏移一个月以前的数据) 
	* @param @param offsetMonthListActivity    设定文件 
	* @return void    返回类型 
	 * @throws Exception 
	* @throws
	 */
	private void processOffsetMonth(List<ListActivityAPIForm> offsetMonthListActivity, long offsetDayTime, long offsetWeekTime, long offsetMonthTime) throws Exception {
		
		LOG.error("开始同步用户观看时长用户观看时长.");
		
		Map<String, LbsGksc> userGkscMap = Maps.newHashMap();
		
		for(ListActivityAPIForm item : offsetMonthListActivity) {
			long activityId = item.getId();
			long pageNo = 1;
			long pageCount = 500;
			
			GetUserBehaviorListResponseAPIV2 apiResponse = liveVideoService.getUserBehaviorDataList(activityId, pageNo, pageCount);
			
			List<UserBehaviorV2> userList = apiResponse.getResult().getData();
			
			if(null == userList) {
				continue ;
			}
			
			processCount(userGkscMap, userList, item.getLiveTime(), offsetDayTime, offsetWeekTime);
			
			if (apiResponse.getResult().getTotalItemCount() > (pageNo * pageCount)) {// 代表一页取完数据
				long countItemSize = apiResponse.getResult().getTotalItemCount();
				long pageSize = (long) Math.ceil((double) countItemSize / pageCount);
				for (int i = 1; i < pageSize; i++) {
					pageNo++;
					apiResponse = liveVideoService.getUserBehaviorDataList(activityId, pageNo, pageCount);
					userList = apiResponse.getResult().getData();
					processCount(userGkscMap, userList, item.getLiveTime(), offsetDayTime, offsetWeekTime);
				}
			}
			
		}
		
		
		//数据入库
		for(String key : userGkscMap.keySet()) {
			LbsGksc lbsGkscItem = userGkscMap.get(key);
			if( null != lbsGkscItem.getId() && lbsGkscItem.getId() != 0 ) {
				lbsGkscService.update(lbsGkscItem);
			}else {
				lbsGkscService.insert(lbsGkscItem);
			}
		}
	}
	
	
	private void processCount(Map<String, LbsGksc> userGkscMap, List<UserBehaviorV2> userList, long liveTime , long offsetDayTime, long offsetWeekTime) {
		
		for(UserBehaviorV2 userBehaviorItem : userList) {
			String userIdStr = userBehaviorItem.getExternalUserId();
			
			if(null == userIdStr || "".equals(userIdStr)) {
				continue;
			}
			
			LbsGksc lbsGksc = null;
			if(userGkscMap.containsKey(userIdStr)) {
				lbsGksc = userGkscMap.get(userIdStr);
			}else {
				long wcUserId = Long.valueOf(userIdStr);
				Member member = memberMapper.selectById(wcUserId);
				if(null == member) { //没有找到对应的会员
					continue;
				}
				lbsGksc = initLbsGksc(member, wcUserId);
				lbsGksc.setMonths(0);
				lbsGksc.setDay(0);
				lbsGksc.setWeeks(0);
				userGkscMap.put(userIdStr, lbsGksc);
			}
			
			//处理月数据
			processMonthCount(lbsGksc, userBehaviorItem.getWatchTime());
			
			if(offsetDayTime < liveTime) { //处理昨日数据
				processDayCount(lbsGksc, userBehaviorItem.getWatchTime());
			}
			
			if(offsetWeekTime < liveTime) { //处理本周数据
				processWeekCount(lbsGksc, userBehaviorItem.getWatchTime());
			}
			
		}
	}
	
	
	private void processMonthCount(LbsGksc lbsGksc, Long watchTime) {
		Integer reMonths = lbsGksc.getMonths();
		if(null == reMonths) {
			reMonths = new Integer(0);
		}
		Long sumTime = (reMonths + watchTime);
		lbsGksc.setMonths(sumTime.intValue());
	}
	
	private void processDayCount(LbsGksc lbsGksc, Long watchTime) {
		Integer reDays = lbsGksc.getDay();
		if(null == reDays) {
			reDays = new Integer(0);
		}
		Long sumTime = (reDays + watchTime);
		lbsGksc.setDay(sumTime.intValue());
	}
	
	private void processWeekCount(LbsGksc lbsGksc, Long watchTime) {
		Integer reWeeks = lbsGksc.getWeeks();
		if(null == reWeeks) {
			reWeeks = new Integer(0);
		}
		Long sumTime = (reWeeks + watchTime);
		lbsGksc.setWeeks(sumTime.intValue());
	}
	
	
	private LbsGksc initLbsGksc(Member member, long wcUserId) {
		QueryWrapper<LbsGksc> qw = new QueryWrapper();
		qw.eq("wc_user_id", wcUserId);
		
		LbsGksc lbsGksc = lbsGkscMapper.selectOne(qw);
		if(null == lbsGksc) {
			lbsGksc = new LbsGksc();
		}
		lbsGksc.setNickname(member.getNickname());
		lbsGksc.setAvatar(member.getAvatar());
		lbsGksc.setDeptDpId(member.getDeptDpId());
		lbsGksc.setDeptTzId(member.getDeptTzId());
		lbsGksc.setDeptZbjId(member.getDeptZbjId());
		lbsGksc.setSpreaduid(member.getSpreaduid());
		lbsGksc.setWcUserId(wcUserId);
		return lbsGksc;
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
